﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace WSDZ.KM.ZH.XiaoManIntegrating40
{
  public class PostHelper
    {
   
        public static string Post(string url, string dataStr, Dictionary<string,string> headerDatas=null,string contentType = "application/json",string accept= "application/json")
        {
            try
            {
                string result = "";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = contentType;
                //req.Accept = accept;
                if (headerDatas!=null)
                {
                    foreach (var h in headerDatas)
                        req.Headers.Add(h.Key, h.Value);
                }
                if (!dataStr.IsNullOrEmptyOrWhiteSpace())
                {
                    byte[] data = Encoding.UTF8.GetBytes(dataStr);//把字符串转换为字节
                    req.ContentLength = data.Length; //请求长度
                    using (Stream reqStream = req.GetRequestStream()) //获取
                    {
                        reqStream.Write(data, 0, data.Length);//向当前流中写入字节
                        reqStream.Close(); //关闭当前流
                    }
                }
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); //响应结果
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                //using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("gbk")))
                //    result = reader.ReadToEnd();
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    result = reader.ReadToEnd();
                return result;
            }
            catch (System.Exception ex)
            {
                return ex.Message;
            }
        }
        public static string PostV1(string url, string dataStr, Dictionary<string, string> headerDatas = null, string contentType = "application/json", string accept = "application/json")
        {
            try
            {
                string result = "";
                url += $@"?{dataStr}";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = contentType;
                req.Accept = accept;
                if (headerDatas != null)
                {
                    foreach (var h in headerDatas)
                        req.Headers.Add(h.Key, h.Value);
                }
                //if (!dataStr.IsNullOrEmptyOrWhiteSpace())
                //{
                //    byte[] data = Encoding.UTF8.GetBytes(dataStr);//把字符串转换为字节
                //    req.ContentLength = data.Length; //请求长度
                //    using (Stream reqStream = req.GetRequestStream()) //获取
                //    {
                //        reqStream.Write(data, 0, data.Length);//向当前流中写入字节
                //        reqStream.Close(); //关闭当前流
                //    }
                //}
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); //响应结果
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                //using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("gbk")))
                //    result = reader.ReadToEnd();
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    result = reader.ReadToEnd();
                return result;
            }
            catch (System.Exception ex)
            {
                return ex.Message;
            }
        }

        public static string PostV2(string url, string dataStr, Dictionary<string, string> headerDatas = null, string contentType = "application/x-www-form-urlencoded")
        {
            try
            {
                string result = "";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = contentType;
                if (headerDatas != null)
                {
                    foreach (var h in headerDatas)
                        req.Headers.Add(h.Key, h.Value);
                }
                if (!dataStr.IsNullOrEmptyOrWhiteSpace())
                {
                    byte[] data = Encoding.UTF8.GetBytes(dataStr);//把字符串转换为字节
                    req.ContentLength = data.Length; //请求长度
                    using (Stream reqStream = req.GetRequestStream()) //获取
                    {
                        reqStream.Write(data, 0, data.Length);//向当前流中写入字节
                        reqStream.Close(); //关闭当前流
                    }
                }
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); //响应结果
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                //using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("gbk")))
                //    result = reader.ReadToEnd();
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    result = reader.ReadToEnd();
                return result;
            }
            catch (System.Exception ex)
            {
                return ex.Message;
            }
        }
        public static string Get(string url, string dataStr, Dictionary<string, string> headerDatas = null, string contentType = "application/json")
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "Get";
                req.ContentType = contentType;
                if (headerDatas != null)
                {
                    foreach (var h in headerDatas)
                        req.Headers.Add(h.Key, h.Value);
                }
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode == HttpStatusCode.OK)
                {

                    Stream stream = resp.GetResponseStream();
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string result = reader.ReadToEnd();
                        return result;
                    }
                }
                else
                {
                    return "接口调用失败";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            
        }
        public static Tuple<bool, TokenData> GetToken(string logType)
        {
            try
            {
                string hstring = $@"{CommonData.client_id}:{CommonData.client_secret}";
                string encodedString = Convert.ToBase64String(Encoding.UTF8.GetBytes(hstring));
                encodedString = $@"Basic {encodedString}";
                Dictionary<string, string> paraDics = new Dictionary<string, string>();
                paraDics.Add("grant_type", "password");
                paraDics.Add("client_id", CommonData.client_id);
                paraDics.Add("client_secret", CommonData.client_secret);
                paraDics.Add("scope", "product company invoices user");
                paraDics.Add("username", CommonData.client_userName);
                paraDics.Add("password", SHA256EncryptToString(CommonData.client_password));
                string dataContent = DicToParameter(paraDics);
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("authorization", encodedString);
                //headers.Add("accept", "application/json");
                //headers.Add("content-type", "application/x-www-form-urlencoded");
                string resultStr = Post(CommonData.tokenUrl,dataContent, headers, "application/x-www-form-urlencoded");
                LogHelper.XiaoManLog($"【获取Token】\n传入:{dataContent}\nheaders:{JsonConvert.SerializeObject(headers)}\n返回:{resultStr}");
                JObject resultObj = JsonConvert.DeserializeObject<JObject>(resultStr);
                string token = resultObj["access_token"].ToStringV1();
                if (token.IsNullOrEmptyOrWhiteSpace())
                    return Tuple.Create(false, new TokenData() { msg="令牌为空"});
                int times= resultObj["expires_in"].ToStringV1().ToInt32V1();
                return Tuple.Create(true, new TokenData() { EndTime=DateTime.Now.AddSeconds(times),token=token });
            }
            catch (Exception ex)
            {
                return Tuple.Create(false, new TokenData() { msg=ex.Message});
            }
        }

        public static string DicToParameter(Dictionary<string, string> dic)
        {
            if (dic == null || dic.Count < 1)
                return "";
            StringBuilder paraStr = new StringBuilder();
            foreach (var obj in dic)
            {
                if (obj.Value != null)
                    paraStr.Append(WebUtility.UrlEncode(obj.Key) + "=" + WebUtility.UrlEncode(obj.Value + "") + "&");
            }
            return paraStr.ToString().Trim('&');
        }

        
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string SHA256EncryptToString(string data)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            byte[] hash = SHA256Managed.Create().ComputeHash(bytes);

            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                builder.Append(hash[i].ToString("x2"));
            }
            return builder.ToString();
        }
        public static Byte[] SHA256EncryptToByte(string str)
        {
            var sha256 = new SHA256Managed();
            var Asc = new ASCIIEncoding();
            var tmpByte = Asc.GetBytes(str);
            var EncryptBytes = sha256.ComputeHash(tmpByte);
            sha256.Clear();
            return EncryptBytes;
        }
    }
}
